;

/**
 * Created by freethy on 2017/1/12.
 */

//加载外部js
//$.getScript("http://oss.ponley.com/oss-h5-upload-js-direct/lib/crypto1/crypto/crypto.js");
//$.getScript("http://oss.ponley.com/oss-h5-upload-js-direct/lib/crypto1/hmac/hmac.js");
//$.getScript("http://oss.ponley.com/oss-h5-upload-js-direct/lib/crypto1/sha1/sha1.js");
//$.getScript("http://oss.ponley.com/oss-h5-upload-js-direct/lib/base64.js");

/* ------------demo-------------------------

 $.upload2oss({
     accessid:    ossid,
     accesskey:   osskey,
     host:        osshost,
     file:file,
     key:"jianhua/rrrr.png",
     success:function(e,option){

     },
     progress:function(e){

     }
 });

*/

/*
 option.accessid    ossid           必填
 option.accesskey   osskey          必填
 option.host        osshost         必填
 option.file         文件             必填
 option.key          远程文件名      必填
 option.args         其他参数
 option.complete     上传完成事件
 option.success      上传成功事件
 option.error        上传出错事件
 option.progress     进度改变事件
 */
jQuery.upload2oss = function(option) {

    option.policyText = {"expiration": "2099-01-01T12:00:00.000Z","conditions": [["content-length-range", 0, 1048576000]]};

    var policyBase64 = Base64.encode(JSON.stringify(option.policyText));
    var bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, option.accesskey, { asBytes: true }) ;
    var signature = Crypto.util.bytesToBase64(bytes);

    var form = new FormData();
    form.append("key", option.key);
    form.append("signature", signature);
    form.append("policy", policyBase64);
    form.append("OSSAccessKeyId", option.accessid);
    form.append("success_action_status", "200");
    form.append("signature", signature);
    form.append("file", option.file);

    var xhr = new XMLHttpRequest();
    xhr.open("post", option.host, true);

    //注册完成事件
    if(typeof (option.complete) != "undefined") {
        xhr.onloadend = function (e) {
            option.complete(e,option);
        }
    };

    //注册成功事件
    if(typeof (option.success) != "undefined") {
        xhr.onload = function (e) {
            option.success(e,option);
        }
    };

    //注册错误事件
    if(typeof (option.error) != "undefined") {
        xhr.onerror = function(e){
            option.error(e,option);
        }
    };

    //注册进度改变事件
    if(typeof (option.progress) != "undefined") {
        xhr.upload.onprogress = function(e){
            e.percent = (100 * (e.loaded / e.total)).toFixed(2);
            option.progress(e,option);
        }
    };

    xhr.send(form);
};

